<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AliOosService;
use app\admin\service\CommissionSettleService;
use app\admin\service\DemandService;
use app\admin\service\OrderService;
use app\admin\service\ResourceSaleWalletService;
use app\admin\service\RoleService;
use app\admin\service\UsersService;
use app\AdminController;
use app\admin\validate\Income as IncomeValidate;
use app\admin\validate\Expenses as ExpensesValidate;

/**
 * 财务管理
 * Class Finance
 * @package app\admin\controller
 */
class Finance extends AdminController
{
    /**
     * 列表
     * @param int $type 1=>订单列表  2=>部门财务  3=>收益明细  4=>支出明细
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($type = 1)
    {
        if (request()->isPost()) {
            $where = [];
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($type == 2) {
                if ($keywords) {
                    $where[] = ['r.name', 'like', '%' . $keywords . '%'];
                }
                $list = CommissionSettleService::getCommissionSettle($where, $this->page, $this->pagesize);
                $count = CommissionSettleService::countCommissionSettle($where);
            } else {
                // 支付
                if ($type == 3) {
                    $where[] = ['o.status', '=', 1];
                    // 退款
                } elseif ($type == 4) {
                    $where[] = ['o.status', '=', 2];
                } else {
                    $where[] = ['o.status', '<>', -1];
                }
                if ($keywords) {
                    $where[] = ['o.order_sn', 'like', '%' . $keywords . '%'];
                }
                $list = OrderService::getAllOrderList($where, $this->page, $this->pagesize, $type);
                $count = OrderService::countAllOrderList($where);
            }

            return adminResponseJson([
                'type' => $type,
                'list' => $list,
                'count' => $count
            ]);
        }

        // 订单总数
        $orderData['totalOrder'] = OrderService::countAllOrder();
        // 收益
        $orderData['totalIncome'] = '+' . sprintf("%.2f", OrderService::orderTotalPayPrice());
        // 支出
        $orderData['totalExpenses'] = '-' . sprintf("%.2f", OrderService::orderTotalRefundPrice());
        // 预计支出
        $orderData['expectedExpenses'] = sprintf("%.2f", CommissionSettleService::sumCommissionSettle(['status' => 0]));
        // 增长比例
        $orderData['increase'] = '10%';
        // 收益（折线图）
        $orderData['totalIncomeLine'] = OrderService::orderTotalPayPriceLine();
        // 支出（折线图）
        $orderData['totalExpensesLine'] = OrderService::orderTotalRefundPriceLine();

        // 市场需求订单数据
        // 成交总金额
        $demandWhere = ['status' => 3];
        $demandData['totalDemandPrice'] = sprintf("%.2f", DemandService::sumDemandPrice($demandWhere));
        // 已完成订单数
        $demandData['totalCompletedDemand'] = DemandService::countDemand($demandWhere);
        // 交接中订单数
        $demandWhere1 = ['status' => 2];
        $demandData['totalHandoverDemand'] = DemandService::countDemand($demandWhere1);
        // 获取钱包数据
        $wallet = ResourceSaleWalletService::getResourceSaleWallet(['type' => 2]);
        // 支出金额
        $demandData['expensesPrice'] = $wallet['expensesPrice'];
        // 预计支出金额
        $demandData['expectedExpensesPrice'] = sprintf("%.2f", DemandService::sumDemandPrice($demandWhere1));
        // 平台收益（这里不累加预计支出的金额）
        $demandData['platformPrice'] = $wallet['platformPrice'];

        // 8.8月会员-查询条件
        $monthWhere = ['mid' => 3, 'type_id' => 1];
        // 8.8月会员-总营业额
        $monthData['orderMonthPrice'] = sprintf("%.2f", OrderService::orderTotalPayPrice($monthWhere));
        // 8.8月会员-总单数
        $monthData['orderMonthTotal'] = OrderService::countOrder($monthWhere);
        // 8.8月会员-复购比例
        $monthData['repurchaseMonthRatio'] = '3%';
        // 8.8月会员-折线图
        $monthData['orderMonthPriceLine'] = OrderService::getOrderPriceLine($monthWhere);

        // 108年会员-查询条件
        $yearWhere = ['mid' => 1, 'type_id' => 1];
        // 108年会员-总营业额
        $yearData['orderYearPrice'] = sprintf("%.2f", OrderService::orderTotalPayPrice($yearWhere));
        // 108年会员-总单数
        $yearData['orderYearTotal'] = OrderService::countOrder($yearWhere);
        // 108年会员-复购比例
        $yearData['repurchaseYearRatio'] = '3%';
        // 108年会员-折线图
        $yearData['orderYearPriceLine'] = OrderService::getOrderPriceLine($yearWhere);

        // 499社群礼包-查询条件
        $resourceWhere = ['mid' => 7, 'type_id' => 15];
        // 499社群礼包-总营业额
        $resourceData['orderResourcePrice'] = sprintf("%.2f", OrderService::orderTotalPayPrice($resourceWhere));
        // 499社群礼包-总单数
        $resourceData['orderResourceTotal'] = OrderService::countOrder($resourceWhere);
        // 499社群礼包-复购比例
        $resourceData['repurchaseResourceRatio'] = '3%';
        // 499社群礼包-折线图
        $resourceData['orderResourcePriceLine'] = OrderService::getOrderPriceLine($resourceWhere);

        return view('index', [
            'type' => $type,
            'orderData' => $orderData,
            'demandData' => $demandData,
            'monthData' => $monthData,
            'yearData' => $yearData,
            'resourceData' => $resourceData,
        ]);
    }

    /**
     * 部门财务
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function branch()
    {
        return $this->index(2);
    }

    /**
     * 部门财务-提交结算
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function branchSettle()
    {
        if (request()->isPost()) {
            $id = intval($this->request->param('id', 0));
            $desc = trim($this->request->param('desc', ''));
            if (!$id) {
                $this->error(adminJsonMsg(1001));
            }
            if (!$desc) {
                $this->error(adminJsonMsg(10019));
            }

            $where = ['id' => $id];
            $info = CommissionSettleService::findCommissionSettle($where);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            $data = CommissionSettleService::updateCommissionSettle(['desc' => $desc, 'sellte_time' => time()], ['id' => $id]);
            if (!$data) {
                $this->error(adminJsonMsg(1003));
            }

            $this->success(adminJsonMsg(1004));
        }
    }

    /**
     * 收益列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function income()
    {
        return $this->index(3);
    }

    /**
     * 收益添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function incomeAdd()
    {
        return $this->handleAddData(3);
    }

    /**
     * 支出列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function expenses()
    {
        return $this->index(4);
    }

    /**
     * 支出添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function expensesAdd()
    {
        return $this->handleAddData(4);
    }

    /**
     * 收益/支出添加
     * @param $source 3=>收益添加  4=>支出添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function handleAddData($source)
    {
        if (request()->isPost()) {
            $data = $this->request->post();

            if ($source == 3) {
                $validate = new IncomeValidate();
                // 订单收益
                $data['type_id'] = 17;
                // 标识为 “支付”
                $data['status'] = 1;
                $data['pay_time'] = strtotime($data['pay_time']);
                $url = (STRING)url('/finance/income') . '?type=3';

            } else {
                $validate = new ExpensesValidate();
                // 订单支出
                $data['type_id'] = 18;
                // 标识为 “退款”
                $data['status'] = 2;
                $data['refund_time'] = strtotime($data['refund_time']);
                $url = (STRING)url('/finance/expenses') . '?type=4';
            }

            $checkResult = $validate->check($data);
            if (!$checkResult) {
                $this->error($validate->getError());
            }

            // 查找经办人是否存在
            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10020));
            }

            $data['create_time'] = time();
            $res = OrderService::createOrder($data);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            // 存储文件到阿里云
            $addPath[] = $data['images'];
            AliOosService::uploadAliOos($addPath);

            $this->success(adminJsonMsg(1004), $url);
        }

        // 部门数据
        $department = $source == 4 ? RoleService::getDepartmentList() : [];
        return view('', ['department' => $department]);
    }
}